package com.liupf.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.util.PathUtil;
import com.liupf.common.utils.Constants;
import com.liupf.domain.Invoice;
import com.liupf.domain.Order;

public class InvoiceController extends Controller {
	private Log log = LogFactory.getLog(this.getClass());

	public void makeInvoice() {
		String id = getPara("id");
		render("assignment_driver.ftl");
	}

	public void invoiceList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
//		int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute("userRole");
		String companyName = getPara("company_name");
		String from = "from invoice a" +
				" left join order_detail b on b.id = a.order_id " +
				" left join b_user bu on b.b_user_id = bu.id " +
				" where 1=1";
		if (StringUtils.isNotBlank(companyName)) {
			from += " and company_name like '%" + StringUtils.trim(companyName)
					+ "%' ";
		}
		from = Constants.appendSqlForRole(from, userRole, company);
		from += " order by id desc";
		Page<Record> page = Db.paginate(getParaToInt(0, 1), 10, "select a.*,bu.job_number ",
				from);
		setAttr("page", page);
		render("invoiceList.ftl");
	}
	
	public void saveInvoice(){
		Integer order_id = getParaToInt();
		setAttr("order_id", order_id);
		
		String sql = "select * from invoice where order_id="+order_id;
		List<Record> recList=Db.find(sql);
		if(recList.size() > 0){
			Record record = recList.get(0);
			setAttr("record", record);
		}
		render("makeInvoice.ftl");
	}
	
	public void addInvoice(){
		Invoice invoice = (Invoice)getModel(Invoice.class);
		String order_id = getPara("order_id");
		String company_name = getPara("company_name");
		String address = getPara("address");
		String person_name = getPara("person_name");
		String phone = getPara("phone");
		String money = getPara("money");
		
		invoice.put("order_id", Long.valueOf(order_id));
		invoice.put("company_name", company_name);
		invoice.put("address", address);
		invoice.put("person_name", person_name);
		invoice.put("phone", phone);
		invoice.put("money", new BigDecimal(money));
		invoice.save();
		
		this.redirect("/invoice/invoiceList");
	}

	public void doMakeInvoice() {
		Integer id = getParaToInt();
		Db.update("update invoice set state=? where id = ?", 1, id);
		log.info(id + ",已开票");
		this.redirect("/invoice/invoiceList");
	}
	
	private void excel(String state) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow((short) 0);
		row.createCell(0).setCellValue("编号");
		row.createCell(1).setCellValue("订单号");
		row.createCell(2).setCellValue("公司抬头");
		row.createCell(3).setCellValue("收件地址");
		row.createCell(4).setCellValue("联系人");
		row.createCell(5).setCellValue("电话");
		row.createCell(6).setCellValue("金额");
		row.createCell(7).setCellValue("状态");
		row.createCell(8).setCellValue("备注");
		List<Record> list;
		String sql = "select * from invoice ";

		list = Db.find(sql);

		for (int i = 0; i < list.size(); i++) {
			HSSFRow r = sheet.createRow(i + 1);
			Record record = list.get(i);
			int memberId = record.getInt("member_id");
			int sex = 0;
			r.createCell(0).setCellValue(record.getInt("id"));
			if (memberId == 0) {
				r.createCell(1).setCellValue(record.getStr("real_name"));
				r.createCell(2).setCellValue(record.getStr("cell_phone"));
				sex = record.getInt("sex");
				r.createCell(4).setCellValue(record.getStr("plage_number"));
			} else {
				r.createCell(1).setCellValue(record.getStr("real_name2"));
				r.createCell(2).setCellValue(record.getStr("cell_phone2"));
				sex = record.getInt("sex2");
				r.createCell(4).setCellValue(record.getStr("plage_number2"));
			}
			if (sex == 0) {
				r.createCell(3).setCellValue("男");
			} else if (sex == 1) {
				r.createCell(3).setCellValue("女");
			} else {
				r.createCell(3).setCellValue("未知");
			}
			r.createCell(5).setCellValue(record.getStr("userarea"));
			r.createCell(6).setCellValue(record.getStr("area_num"));
			r.createCell(7).setCellValue(record.getStr("startpoint"));
			r.createCell(8).setCellValue(record.getStr("endpoint"));
			r.createCell(9).setCellValue(
					record.getBigDecimal("kilometre").toString());
			r.createCell(10).setCellValue(
					record.getBigDecimal("totalmoney").toString());
			int payType = record.getInt("pay_type");
			if (payType == 0) {
				r.createCell(11).setCellValue("现金");
			} else if (payType == 1) {
				r.createCell(11).setCellValue("企业支付");
			} else if (payType == 2) {
				r.createCell(11).setCellValue("VIP支付");
			} else {
				r.createCell(11).setCellValue("免费客户");
			}
			int orderType = record.getInt("order_type");
			if (orderType == 0) {
				r.createCell(12).setCellValue("普通");
			} else if (orderType == 1) {
				r.createCell(12).setCellValue("企业订单");
			} else if (orderType == 2) {
				r.createCell(12).setCellValue("酒店订单");
			} else if (orderType == 3) {
				r.createCell(12).setCellValue("KTV订单");
			}

			r.createCell(13).setCellValue(record.getStr("driver_name"));
			r.createCell(14).setCellValue(record.getStr("job_number"));
			r.createCell(15).setCellValue(record.getStr("driver_phone"));

			Timestamp ts1 = record.getTimestamp("create_time");
			r.createCell(16).setCellValue(ts1 == null ? "" : ts1.toString());
			Timestamp ts2 = record.getTimestamp("publish_time");
			r.createCell(17).setCellValue(ts2 == null ? "" : ts2.toString());
			Timestamp ts3 = record.getTimestamp("accept_time");
			r.createCell(18).setCellValue(ts3 == null ? "" : ts3.toString());
			Timestamp ts4 = record.getTimestamp("arrived_time");
			r.createCell(19).setCellValue(ts4 == null ? "" : ts4.toString());
			Timestamp ts5 = record.getTimestamp("driver_begin_time");
			r.createCell(20).setCellValue(ts5 == null ? "" : ts5.toString());
			Timestamp ts6 = record.getTimestamp("driver_finish_time");
			r.createCell(21).setCellValue(ts6 == null ? "" : ts6.toString());

			String cancel = record.getStr("cancel") == null ? "" : record
					.getStr("cancel");
			String cancelDriver = record.getStr("cancel_driver") == null ? ""
					: record.getStr("cancel_driver");
			r.createCell(22).setCellValue(cancel + cancelDriver);
			r.createCell(23).setCellValue(
					record.getStr("cancel_approval_opinion"));
			r.createCell(24).setCellValue(record.getStr("complaint_content"));
			r.createCell(25).setCellValue(
					record.getStr("complain_approval_opinion"));
		}
		PathUtil.getWebRootPath();
		String fileName = PathUtil.getWebRootPath() + "/excel/"
				+ System.currentTimeMillis() + "_" + new Random().nextLong()
				+ ".xls";
		File f = new File(fileName);
		log.debug("file path:" + f.getAbsolutePath());
		FileOutputStream fOut;
		try {
			fOut = new FileOutputStream(fileName);
			workbook.write(fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
			throw new RuntimeException("导出excel失败，请稍后再试", e);
		}
		renderFile(f);
	}
}
